<template>
  <a-modal
    v-model:open="open"
    centered
    cancel-text="返回编辑"
    ok-text="添加"
    :title="`添加重点${propsMap[keyType]}`"
    :mask-closable="false"
    @ok="confirmAdd"
    @cancel="cancelAdd"
  >
    <a-form ref="formRef" :model="formState" :rules="rules" style="width: 80%; paddingtop: 20px">
      <a-form-item :label="`${propsMap[keyType]}名称`" name="keyName">
        <a-input v-model:value="formState.keyName" />
        <span v-if="isRepetition" style="margin: 2px 4px; color: #da3a32; fontsize: 12px">名称重复</span>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref, reactive, watch, type UnwrapRef } from 'vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { useEquipmentInfo } from '@/store/modules/equipmentInfo'

  interface FormState {
    keyName: string
  }

  interface Props {
    keyType: 'area' | 'target' | ''
  }

  const $equipmentInfo = useEquipmentInfo()

  const props = withDefaults(defineProps<Props>(), {
    keyType: 'area'
  })
  const propsMap = {
    area: '区域',
    target: '目标'
  }

  const emit = defineEmits(['confirm-add', 'cancel-add'])

  const open = ref<boolean>(false)
  const isRepetition = ref<boolean>(false)
  const formRef = ref()
  const formState = reactive<UnwrapRef<FormState>>({
    keyName: ''
  })
  const extraProperties = ref<Record<string, any>>()

  const rules: Record<string, Rule[]> = {
    keyName: [{ required: true, message: '名称必填' }]
  }

  /**
   * 确认添加区域和目标，同时校验名称是否重复
   * 关闭弹窗，清除 form 内容
   * 同时取消画线
   */
  const confirmAdd = () => {
    formRef.value.validate().then((res) => {
      emit('confirm-add')

      validateInfoName()
      // this.drawLayers.temp = this.drawLayer;
      console.log('res', res)
      props.keyType === 'area' &&
        $equipmentInfo.addInfo('area', {
          ...res,
          id: Math.random(),
          extraProperties: { polygon: extraProperties.value }
        })
      props.keyType === 'target' &&
        $equipmentInfo.addInfo('target', { ...res, id: Math.random(), extraProperties: extraProperties.value })

      formRef.value.resetFields()

      open.value = false
    })
  }

  const cancelAdd = () => {
    open.value = false
    formRef.value.resetFields()
    isRepetition.value = false

    emit('cancel-add')
  }
  /* 校验输入名称是否重复 */
  const validateInfoName = () => {
    if (!formState.keyName) {
      return
    }

    const sessionData = $equipmentInfo.getData()

    const validateInfoNameMap = {
      area: 'areaInfo',
      target: 'targetInfo'
    }

    const dataRes = sessionData[validateInfoNameMap[props.keyType]]

    const validate = (data) => {
      data.forEach((item) => {
        if (formState.keyName === item.keyName) {
          isRepetition.value = true
          throw new Error('isRepetition')
        } else {
          isRepetition.value = false
        }
      })
    }

    validate(dataRes)
  }

  watch(
    () => formState.keyName,
    () => {
      validateInfoName()
    }
  )

  defineExpose({ open, extraProperties })
</script>
